<template>
  <div class="plc bg-white page-content content padding-l-20 padding-t-20 padding-r-20" ref="plc">
    <div></div>
    <online-card
      :titleList="[`实时数据(共${pointSize}个点位),最后更新时间: ${updateTime}`]"
      :height="290"
      :isCardType="false"
    >
      <template slot="header">
<!-- 根据华赢租户id（52641623953010688）显示 -->
<!--        v-if="userInfo.tenant_id === '52641623953010688'"-->
        <div class="flex items-center">
          <div class="q-mr-md">
            <q-radio v-model="dataSize" :val="2" label="二列排版" />
            <q-radio v-model="dataSize" :val="3" label="三列排版" />
            <q-radio v-model="dataSize" :val="4" label="四列排版" />
            <q-radio v-model="dataSize" :val="5" label="五列排版" />
          </div>
          <q-btn
            style="font-size: 18px"
            flat
            round
            dense
            v-if="userInfo.tenant_id === '52641623953010688'"
            color="primary"
            class="iconfont iconqita-10"
            @click="setClassification"
          >
            <q-tooltip>分类</q-tooltip>
          </q-btn>
          <q-btn
            style="font-size: 18px"
            flat
            round
            dense
            color="primary"
            class="iconfont icontubiao2-97"
            @click="setPLC"
          >
            <q-tooltip>设置</q-tooltip>
          </q-btn>
        </div>
      </template>
      <template slot="content">
        <div class="padding-20 scrollbar overflow-auto content">
          <div class="row" v-for="(item, index) in dataArray" :key="index">
            <div class="text" :class="col[dataSize]" v-for="(data, dataIndex) in item" :key="`index${dataIndex}`">
              <span class="title">{{data.key}}:</span>
              <span class="normal" v-if="!data.isRed">{{data.value}}</span>
              <span class="error" v-else>{{data.value}}</span>
            </div>
          </div>
        </div>
      </template>
    </online-card>
    <div class="margin-t-20">
      <online-card
        :titleList="policeList"
        :height="400"
        :infoValue="infoValue"
        @getChangeInfo="getChangePolice"
        isShowPoliceInfo
        :isCardType="false"
      >
        <template slot="content">
          <y-police  ref="YPolice" @isShowYPolice="isShowYPolice" v-show="infoValue === 1"></y-police>
          <callPolice ref="callP" @isShowPolice="onShowPolice"  v-show="infoValue === 2"/>
        </template>
      </online-card>
    </div>
    <!--  设置分类  -->
    <classification ref="classification"/>
    <plcThresholdSetPannel :show="setDialog" :processData="processData"  @close="setDialog=false"/>
  </div>
</template>

<script>
/* eslint-disable */
import onlineCard from './components/online-process/online-card'
import callPolice from './components/online-process/call-police'
import plcThresholdSetPannel from './components/plc-threshold-set-pannel'
import { mapGetters } from 'vuex'
import _ from 'lodash'
import { getPlcData } from '../../boot/status-monitor/machine'
import moment from 'moment'
import YPolice from './components/online-process/y-police'
import classification from './components/classification'
import { userInfo } from '../../store/getters'

export default {
  name: 'monitor',
  components: {
    YPolice,
    onlineCard,
    callPolice,
    plcThresholdSetPannel,
    classification
  },
  props: {
    processData: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapGetters(['client', 'statusList', 'userInfo'])
  },
  watch: {
    processData: {
      deep: true,
      immediate: true,
      handler: function (val) {
        if (val) {
          if (val.id) {
            console.log(this.client)
            // 先取消订阅,然后再订阅
            this.client.unsubscribe('plcTopic')
            this.getInitData(val.id)
            this.onSubscribe(val.id)
            this.$nextTick(() => {
              this.$refs.callP?.getMachineStatusDetails(val)
              this.$refs.YPolice?.getMachineYDetails(val)
            })
          }
        }
      }
    },
    dataSize () {
      this.dataArray =  _.chunk(Object.keys(this.dataObj).map(item => this.dataObj[item]), this.dataSize)
    }
  },
  mounted () {
    this.$set(this.policeList[1],'label', `设备${this.statusList?.[4]?.label}信息`)
  },
  data () {
    return {
      policeLength: 0,
      yPoliceLength: 0,
      setDialog: false,
      dataObj: {},
      dataArray: [[]],
      dataSize: 4,
      col: {
        2: 'col-6',
        3: 'col-4',
        4: 'col-3',
        5: 'col-2',
      },
      pointSize: 0,
      updateTime: '',
      infoValue: 1,
      policeList: [{
        label: '阈值报警信息',
        value: 1,
        tip: 0
      },{
        label: `设备报警信息`,
        value: 2,
        tip: 0
      }]
    }
  },
  methods: {
    getChangePolice(val) {
      this.infoValue = val.value
    },
    getInitData(deviceId) {
      this.dataObj = {}
      getPlcData(deviceId).then(res => {
        this.handleResData(res.data)
      })
    },
    handleResData(data) {
      console.log(data)
      const member = data?.plcPointSocketResVOS
      const updateTime = Number(data?.updateTime) * 1000
      if (!isNaN(updateTime)) {
        this.updateTime = moment(updateTime).format('YYYY-MM-DD HH:mm:ss')
      }
      // 将数据放在obj中，如果字段存在将更新
      if (Array.isArray(member)) {
        member.forEach(item => {
          this.dataObj[item.key] = item
        })
      }
      this.pointSize = Object.keys(this.dataObj).length
      // 根据obj的key，获取value，并拆分数组为二维数组，一行四个
      this.dataArray =  _.chunk(Object.keys(this.dataObj).map(item => this.dataObj[item]), this.dataSize)
    },
    // 订阅plc的消息
    onSubscribe (deviceId) {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.PLC.subscribeTopic}${deviceId}`, this.getPLCType, { id: `plcTopic` }
        )
        this.$once('hook:beforeDestroy', () => {
          this.client.unsubscribe('plcTopic')
        })
      } else {
        setTimeout(() => {
          this.onSubscribe(deviceId)
        }, 1000)
      }
    },
    getPLCType (res) {
      // 获取消息体
      let member = JSON.parse(res.body).data
      this.handleResData(member)
    },
    // 是否显示报警列表
    onShowPolice (val) {
      this.policeLength = val
      this.$set(this.policeList[1],'tip',  this.policeLength)
    },
    isShowYPolice (val) {
      this.yPoliceLength = val
      this.$set(this.policeList[0],'tip',  this.yPoliceLength)
    },
    // 显示plc弹框
    setPLC () {
      this.setDialog = true
    },
    // 设置分类
    setClassification(){
      this.$refs.classification.showDialog(this.processData.deviceId)
    }
  }
}
</script>

<style scoped lang="scss">
.content{
  max-height: 240px;
}
.text{
  font-size: 16px;
  line-height: 1;
  border: 1px solid #eee;
  height: 44px;
  padding-top: 6px;
  padding-left: 6px;
  .normal{
    margin-left: 8px;
  }
  .error{
    color: #E43434;
  }
}
</style>
